package com.itcam.list_.collection_;

import com.itcam.list_.collection_.domain.Student;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Consumer;

/**
 * Author:Cammy.Wu
 * Date:2024-05-17
 * Description: public Iterator<E> iterator(); : 获取遍历集合的迭代器
 */

public class CollectionDemo02 {
    /**
     * public Iterator<E> iterator():获取遍历集合的迭代器
     * public E next():从集合中获取一个元素
     * public boolean hasNext():如果仍有元素可以迭代，则返回true
     * <p>
     * 注意：如果next()方法调用次数过多，会出现NoSuchElementException
     */
    public static void main(String[] args) {
        Collection<Student> c = new ArrayList<>();

        c.add(new Student("cammy", 24));
        c.add(new Student("jerry", 20));
        c.add(new Student("tim", 35));

        // 1.获取迭代器
        Iterator<Student> itt = c.iterator();

        // 2.循环判断，集合中是否还有元素
//        while (true) {
//            try {
//                Student s = itt.next();
//                System.out.println("s = " + s);
//            } catch (NoSuchElementException e) {
//                break;
//            }
//        }
        while (itt.hasNext()) {
            // 3.调用next方法，将元素取出
            Student stu = itt.next();
            System.out.println("stu = " + stu);
        }

        System.out.println("-----------------------------------------------------");

        // 使用增强for循环遍历集合
        for (Student student : c) {
            System.out.println("student = " + student);
        }

        System.out.println("-----------------------------------------------------");

        // forEach方法遍历集合
//        c.forEach(new Consumer<Student>() {
//            @Override
//            public void accept(Student student) {
//                System.out.println("student = " + student);
//            }
//        });
        c.forEach(student -> System.out.println("student = " + student));
    }
}
